<?php
/**
 *
 *
 *
 */
class Yz_Action_SelectNeighbors
    extends Yz_Action_Select
{

    /**
     *  @var int ?
     */
    protected $id;
    protected $order;

    /**
     *  @param int id > 0
     *  @return this
     */
    public function setId( $id )
    {
        debug();
        $this->id = Yz_Int::testPositive($id);
        return $this;
    }


    /**
     *  @return array(0: Item previous, 1: Item next)
     */
    public function fetch()
    {
        if (! $this->executed)
            throw new Yz_Action_Exception_NotExecutedYet();
        return $this->statement->fetchAll();
    }


    /************************************
     *        Protected methods         *
     ************************************/


    /**
     *  Build the common part of the SQL statement
     *  @abstract
     *  @return Yz_SQL_Statement
     */
    protected function buildStatement()
    {
        $this->inspectModel();
        $fields = $this->fields;
        $sqlPrev = Yz_SQL_Statement_Select::create()
            ->select($fields)
            ->from($this->tables)
        ;
        $sqlNext = Yz_SQL_Statement_Select::create()
            ->select($fields)
            ->from($this->tables)
        ;
        $source = $this->model->getName();
        $sqlNext
        // create two SQL Selects
            ->where("{$source}.id > :_id")
            ->orderBy("{$source}.id ASC")
            ->limit(1)
        ;
        $sqlPrev
            ->where("{$source}.id < :_id")
            ->orderBy("{$source}.id DESC")
            ->limit(1)
        ;
        return $sqlPrev->union($sqlNext);
    }


    /**
     *  Apply the arguments to the SQL statement
     *  @param Yz_SQL_Statement $sql
     *  @return this
     */
    protected function applyArguments(Yz_SQL_Statement $sql)
    {
        debug();
        $sql->bind('_id', $this->id) ;
        return $this;
    }


}
